<?php
namespace App\Services;
use Illuminate\Support\Facades\Redis;

class RedisTool
{
    const LOCK_SUCCESS = 'OK';
    const RELEASE_SUCCESS = 1;

    /**
     * 尝试获取锁
     * @param String $key               锁
     * @param String $requestId         请求id
     * @param int $expireTime           过期时间
     * @return bool                     是否获取成功
     */
    public static function tryGetLock(String $key, int $expireTime, String $requestId) {

        $lua ="return redis.call('SET', KEYS[1], ARGV[1], 'NX', 'EX', ARGV[2])";

        $result = Redis::eval($lua, 1,$key, $requestId, $expireTime);
        return self::LOCK_SUCCESS === (String)$result;
    }


    /**
     * 解除锁
     * @param String $key               锁
     * @param String $requestId         请求id
     */
    public static function releaseLock( String $key, String $requestId) {
        $lua = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";

        $result = Redis::eval($lua, 1, $key, $requestId);
        return self::RELEASE_SUCCESS === $result;
    }
}
